package Thread2;

import java.util.PriorityQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{

    private Runnable task;
    // 记录要执行的任务时刻
    private long time;

    public MyTimerTask2(Runnable task,long time){
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }

    public long getTime(){
        return time;
    }

    public void run(){
        task.run();
    }
}

// 自己设计一个定时器
class MyTimer2{
    private PriorityQueue<MyTimerTask2> queue = new PriorityQueue<>();

    private Object locker = new Object();
    public void schedule(Runnable task,long delay){
        synchronized (locker){
            MyTimerTask2 timerTask = new MyTimerTask2(task,System.currentTimeMillis()+ delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    public MyTimer2(){
        // 创建一个线程,完成执行队列中的任务
        Thread t = new Thread(() -> {
            try{
                while(true){
                    synchronized (locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask2 task = queue.peek();
                        if(System.currentTimeMillis() < task.getTime()){
                            // 当前任务时间比系统时间大,说明任务执行的时间还没到
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        }else {
                            // 时间到了,执行任务
                            task.run();
                            queue.poll();
                        }
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t.start();
    }

}
public class Homework8 {
    public static void main(String[] args) {
        MyTimer2 timer = new MyTimer2();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        },3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        },2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        },1000);
    }
}
